<style lang="less">
  .to-appointment-visible {
    .flex {
      display: flex;
      justify-content: space-between;
      .input {
        width: 110px;
        margin-right: 1em;
      }
      button, select {
        flex: 1 1 0;
      }
    }
    .smt {
      display: flex;
      justify-content: flex-end;
      .ivu-btn-long {
        width: auto;
      }
    }
    .ivu-form-item {
      margin-bottom: 15px;
      vertical-align: top;
      zoom: 1;
    }
    .check-code {
      cursor: pointer;
    }
  }
</style>

<template>
  <Modal
    v-model="toAppointmentVisible"
    title="立即预约"
    width="350"
    class-name="to-appointment-visible"
    @on-cancel="cancel">
    <Form :model="form" label-position="left" :label-width="100">
      <Form-item label="手机号">
        <Input v-model="form.phone"/>
      </Form-item>
      <Form-item label="图形码">
        <div class="flex">
          <div class="input">
            <Input v-model="form.pic"/>
          </div>
          <img class="check-code" @click="init" :src="picPath" alt="">
        </div>
      </Form-item>
      <Form-item label="验证码">
        <div class="flex">
          <div class="input">
            <Input v-model="form.code"/>
          </div>
          <Button type="primary" :disabled="!isDisabledSendButton" @click="sendValidCode">发送验证码
            <span v-if="!isDisabledSendButton">({{toAppointmentCount}}秒)</span>
          </Button>
        </div>
      </Form-item>
      <Form-item label="预约">
        <div class="flex">
          <div class="input">
            <Date-picker v-model="form.orderTime" type="date" placeholder="选择日期"></Date-picker>
          </div>
          <select v-model.number="form.number">
            <option value="1">1人</option>
            <option value="2">2人</option>
            <option value="3">3人</option>
            <option value="4">4人</option>
          </select>
        </div>
      </Form-item>
    </Form>
    <div slot="footer" class="smt">
      <Button size="large" @click="cancel">取消</Button>
      <Button type="primary" size="large" long :loading="loading" @click="createOrder">确定</Button>
    </div>
  </Modal>
</template>


<script>
  import store from '@/store/global'
  import api from '@/service/api'

  let phoneRe = /^1\d{10}$/
  let codeRe = /^\d{6}$/
  let codePicRe = /[a-zA-Z0-9]{4}/

  let defaultForm = {
    phone: '',
    orderTime: new Date(),
    code: '',
    number: 1,
    pic: ''
  }
  export default {
    store,
    data () {
      return {
        form: {...defaultForm},
        countDown: 60,
        loading: false,
        picPath: '',
        clickable: 1,
        picId: 0,
        isMatch: false,
      }
    },
    computed: {
      isDisabledSendButton () {
        return this.toAppointmentCount <= 0
      },
      ...Vuex.mapState([
        'toAppointmentVisible',
        'category',
        'houseId',
        'toAppointmentCount'
      ])
    },
    methods: {
      createOrder () {
        let postData = {
          ...this.form,
          category: this.category,
          orderId: this.houseId
        }

        postData.orderTime = moment(postData.orderTime).format()

        if (!phoneRe.test(this.form.phone.trim())) {
          this.$Notice.error({
            title: '手机号错误',
            desc: '请输入11位手机号'
          })
          return
        }

        this.loading = true
        api.isOrder(this.form.phone, this.houseId, this.category).then((res) => {
          if (res.data.isExist === false) {
            api.createOrder(postData).then((res) => {
              this.loading = false
              if (res.data.status === true) {
                store.commit('hideAppointmentVisible')
                this.form = {...defaultForm}
                this.$Notice.success({
                  title: '预约成功',
                  desc: res.data.result
                })
              } else {
                this.$Notice.error({
                  title: '预约失败',
                  desc: res.data.result
                })
              }
            }).catch((e) => {
              this.loading = false
              this.$Notice.error({
                title: '预约失败',
                desc: e ? e.toString() : '未知原因'
              })
            })
          } else {
            this.$Notice.error({
              title: '预约失败',
              desc: `您已经预约过该房源`
            })
          }
        }).catch((e) => {
          this.$Notice.error({
            title: '预约失败',
            desc: `网络异常` + e
          })
        })
      },
      cancel () {
        store.commit('hideAppointmentVisible')
        this.form = {...defaultForm}
      },
      sendValidCode () {
        // 验证手机号
        if (!phoneRe.test(this.form.phone.trim())) {
          this.$Notice.error({
            title: '手机号错误',
            desc: '请输入11位手机号'
          })
          return
        }

        //图文码验证
        if (!codePicRe.test(this.form.pic.trim())) {
          this.$Notice.error({
            title: '验证码',
            desc: '请输入4位图文验证码'
          })
          return
        }

        this.checkPic().then((res) => {
          this.isMatch = res.data.isSuccess
          if (!this.isMatch) {
            this.$Notice.error({
              title: '验证码',
              desc: '请输入验证码有误'
            })
            return
          }
          
          api.isOrder(this.form.phone, this.houseId, this.category).then((res) => {
            if (res.data.isExist === false) {
              this.$store.dispatch('subtractionCountDown')
              api.smsCode(this.form.phone).then((res) => {
                this.disabled = false
                if (res.data.status === true) {
                  this.$Notice.success({
                    title: '发送成功',
                    desc: '验证码已发送，请注意查收'
                  })
                } else {
                  this.$Notice.error({
                    title: '发送验证码失败',
                    desc: res.data.result
                  })
                }
              }).catch((err) => {
                this.disabled = false
                this.$Notice.error({
                  title: '发送验证码失败',
                  desc: `发送失败 ${err ? err.toString() : ''}}`
                })
              })
            } else {
              this.$Notice.error({
                title: '预约失败',
                desc: `您已经预约过该房源`
              })
            }
          }).catch((e) => {
            this.$store.dispatch('subtractionCountDown')
            this.$Notice.error({
              title: '无法获取验证码',
              desc: e ? e.toString() : '原因未知'
            })
          })
        }).catch((e) => {
          this.$Notice.success({
            title: '错误',
            desc: '检查验证码失败'
          })
        })
      },
      checkPic () {
        return api.validate(this.id, this.form.pic)
      },
      init () {
        this.clickable--
        if (this.clickable === 0) {
          api.validatePic().then((response) => {
            this.picPath = response.data.path
            this.id = response.data.id
            this.clickable = 1
          })
        }
      }
    },
    created () {
      this.init()
    }
  }
</script>
